//
//  AppDelegate.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/1/12.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "AppDelegate.h"
#import "HomeTabBarVC.h"
#import "IQKeyboardManager.h"
#import "HomeViewController.h"
#import "LoginViewController.h"
#import "HomeTabBarVC.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h>
#import <WXApiObject.h>

#define WXAPPID @"testtesttesttest"


@interface AppDelegate () <WXApiDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
//    if (@available(iOS 11.0, *)) {
//        UITableView.appearance.estimatedRowHeight = 0;
//        
//        UITableView.appearance.estimatedSectionFooterHeight = 0;
//        
//        UITableView.appearance.estimatedSectionHeaderHeight = 0;
//        
//        UITableView.appearance.contentInsetAdjustmentBehavior =  UIScrollViewContentInsetAdjustmentNever;
//        
//    }
    
    self.window.backgroundColor =[UIColor whiteColor];
    [WXApi registerApp:WXAPPID];
    [self IQkeyBoard];
    [self startRootVC];
    return YES;
}

- (void)IQkeyBoard {
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    [IQKeyboardManager sharedManager].toolbarTintColor = APP_DEFAULT_COLOUR;
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"完成";
    manager.keyboardDistanceFromTextField =44;
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES; //控制点击背景是否收起键盘
}

// 启动
-(void)startRootVC
{
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    NSString * phoneStr = [TheGlobalMethod getUserDefault:@"phone"];
    NSString * codeStr = [TheGlobalMethod getUserDefault:@"code"];
    
    
//    HomeTabBarVC *tabBarVC =[[HomeTabBarVC alloc]init];
//    self.window.rootViewController = tabBarVC;
//    [self.window makeKeyAndVisible];
//    return;
    
    if ([[TheGlobalMethod getUserDefault:@"code"] length] > 0)
    {
        [HttpUrl NetErrorGET:@"user/loginPhone" dict:@{@"phone":phoneStr,@"code":codeStr} hud:[UIApplication sharedApplication].keyWindow isShow:NO WithSuccessBlock:^(id data) {
            if (BB_isSuccess) {
                [TheGlobalMethod insertUserDefault:[data[@"data"][@"token"] description] Key:@"token"];
                [TheGlobalMethod insertUserDefault:[data[@"data"][@"headImg"] description] Key:@"headImg"];
                [TheGlobalMethod insertUserDefault:[data[@"data"][@"userName"] description] Key:@"userName"];
                [TheGlobalMethod insertUserDefault:[data[@"data"][@"id"] description] Key:@"usrid"];
                HomeTabBarVC *tabBarVC =[[HomeTabBarVC alloc]init];
                self.window.rootViewController = tabBarVC;
                [self.window makeKeyAndVisible];
            }
            else{
                LoginViewController *loginVC =[[LoginViewController alloc]init];
                BaseNavController *homeNav =[[BaseNavController alloc]initWithRootViewController:loginVC];
                self.window.rootViewController = homeNav;
                [self.window makeKeyAndVisible];
            }
        
        } WithFailBlock:^(id data) {
           // 没网路
            LoginViewController *loginVC =[[LoginViewController alloc]init];
            BaseNavController *homeNav =[[BaseNavController alloc]initWithRootViewController:loginVC];
            self.window.rootViewController = homeNav;
            [self.window makeKeyAndVisible];
            [JXTAlertView showAlertViewWithTitle:@"提示" message:@"连接网络失败" cancelButtonTitle:nil buttonIndexBlock:^(NSInteger buttonIndex) {
            } otherButtonTitles:@[@"确定"]];
            

        }];
    } else {
        LoginViewController *loginVC =[[LoginViewController alloc]init];
        BaseNavController *homeNav =[[BaseNavController alloc]initWithRootViewController:loginVC];
        self.window.rootViewController = homeNav;
        [self.window makeKeyAndVisible];
    }


}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
        return YES;
    }
    return [WXApi handleOpenURL:url delegate:self];
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
        
        // 授权跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processAuth_V2Result:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            // 解析 auth code
            NSString *result = resultDic[@"result"];
            NSString *authCode = nil;
            if (result.length>0) {
                NSArray *resultArr = [result componentsSeparatedByString:@"&"];
                for (NSString *subResult in resultArr) {
                    if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                        authCode = [subResult substringFromIndex:10];
                        break;
                    }
                }
            }
            NSLog(@"授权结果 authCode = %@", authCode?:@"");
        }];
    }
    return YES;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {

    return [WXApi handleOpenURL:url delegate:self];
}

- (void)onResp:(BaseResp *)resp {
    
    NSLog(@"on resp : %@", resp);
    
    if ([resp isKindOfClass:[SendAuthResp class]])
    {
        SendAuthResp *rep = (SendAuthResp *)resp;
        if (rep.errCode == 0) {
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WXSuccessLogin" object:@{@"code":rep.code}];
        }
        
    }
    
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
